const path = require('path')
const os = require("os")
const axios= require("axios")
const iconv = require("iconv-lite")
const md5 =require('blueimp-md5')
const moment = require('moment-timezone')
const Base64 = require('js-base64').Base64
function getRootPath() {
  return path.resolve(process.cwd())
}
const rootPath = getRootPath()

//获取IP属地
async function fetchAddress(ip) {
  const http = axios.create({
    baseURL: ``,
    responseType: "arraybuffer"
  })

  http.interceptors.response.use(res => {
      res.data = iconv.decode(res.data, 'gbk')
      return res
  })
  // return await http.get(`http://whois.pconline.com.cn/ip.jsp?ip=${getNetworkIp()}`)
  return await http.get(`http://whois.pconline.com.cn/ip.jsp?ip=${ip}`)
};

function checkFileSuffix(ext){
  const type = ['jpg','jpeg','png','gif','bmp','svg'];
  if(!ext) return false;
  return type.includes(ext);
}

function getUserLever(exp) {
  let lever = 0
  exp = exp - 0
  if (exp > 0) lever = 1
  if (exp > 30) lever = 2
  if (exp > 110) lever = 3
  if (exp > 290) lever = 4
  if (exp > 592) lever = 5
  if (exp > 1168) lever = 6
  if (exp > 2190) lever = 7
  if (exp > 3650) lever = 8
  if (exp > 7350) lever = 9
  if (exp > 11250) lever = 10
  if (exp > 15450) lever = 11
  if (exp > 20222) lever = 12
  if (exp > 26626) lever = 13
  if (exp > 33366) lever = 14
  if (exp > 40028) lever = 15
  if (exp > 48000) lever = 16
  return lever
}
//生成六位随机数
function randomCode(length) {
    var chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
    var result = ""; //统一改名: alt + shift + R
    for (var i = 0; i < length; i++) {
        var index = Math.ceil(Math.random() * 9);
        result += chars[index];
    }
    return result;
}

//发送验证码
async function sendCode(phone,code) {
    var ACCOUNT_SID = "8aaf0708842397dd01845c9985441248";
    var AUTH_TOKEN = "1a4a67a6a51e49b682a1b2bdf991bb12";
    var Rest_URL = "https://app.cloopen.com:8883";
    var AppID = "8aaf0708842397dd01845c99862c124f";
    //1. 准备请求url
    /*
    1.使用MD5加密（账户Id + 账户授权令牌 + 时间戳）。其中账户Id和账户授权令牌根据url的验证级别对应主账户。
    时间戳是当前系统时间，格式"yyyyMMddHHmmss"。时间戳有效时间为24小时，如：20140416142030
    2.SigParameter参数需要大写，如不能写成sig=abcdefg而应该写成sig=ABCDEFG
     */
    var sigParameter = "";
    var time = moment().format("YYYYMMDDHHmmss");
    sigParameter = md5(ACCOUNT_SID + AUTH_TOKEN + time);
    sigParameter = sigParameter.toUpperCase()
    var url = Rest_URL + "/2013-12-26/Accounts/" + ACCOUNT_SID + "/SMS/TemplateSMS?sig=" + sigParameter;
    //2. 准备请求体
    var body = {
        to: phone,
        appId: AppID,
        //模板ID
        templateId: "1",
        "datas": [code, "1"]
    }
       //3. 准备请求头
    /*
    1.使用Base64编码（账户Id + 冒号 + 时间戳）其中账户Id根据url的验证级别对应主账户
    2.冒号为英文冒号
    3.时间戳是当前系统时间，格式"yyyyMMddHHmmss"，需与SigParameter中时间戳相同。
     */
    var authorization = ACCOUNT_SID + ":" + time;
    authorization = Base64.encode(authorization);
    var headers = {
        "Accept": "application/json",
        "Content-Type": "application/json;charset=utf-8",
        "Content-Length": JSON.stringify(body).length + "",
        "Authorization": authorization
    }
    let flag = false
    try{
      await axios({
          method:'post',
          url: url,
          headers:headers,
          data: body,
      }).then((res)=>{
          if(res.data.statusCode=='000000'){
            flag = true
          }else{
            flag = false
          }
      })
      
    } catch(err){
      console.log('出错了')
    }

    console.log(flag);
    if(flag){
      return {phone,code}
    }else{
      console.log('出错了')
    }
}
function getMaterialSrc (content) {
  let list = [];
  content.replace(
    /<img [^>]*src=['"]([^'"]+)[^>]*>/g,
    (match, capture) => {     
      list.push(capture);
      return match;
    }
  );
}
module.exports = {
  getRootPath,
  rootPath,
  getUserLever,
  fetchAddress,
  checkFileSuffix,
  sendCode,
  randomCode,
  getMaterialSrc
}